<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>购物车</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #333;
        }
        .cart-wrapper {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .cart-container {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            width: 90%;
            max-width: 900px;
            margin: 0 auto;
        }
        .cart-item {
            width: 100%;
            height: 180px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 15px;
            box-sizing: border-box;
            display: flex;
            transition: transform 0.3s ease;
            overflow: hidden;
        }
        .cart-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        .goods-img {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 4px;
            margin-right: 15px;
            flex-shrink: 0;
        }
        .item-details {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-width: 0;
        }
        .item-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .item-price {
            font-size: 15px;
            color: #e53935;
            margin-bottom: 12px;
        }
        .quantity-control {
            display: flex;
            align-items: center;
            margin-bottom: 12px;
        }
        .quantity-control button {
            width: 28px;
            height: 28px;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
        }
        .quantity-control button:hover {
            background-color: #e0e0e0;
        }
        .quantity-control input {
            width: 40px;
            height: 28px;
            text-align: center;
            margin: 0 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        .delete-btn, .checkout-btn {
            padding: 6px 12px;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            transition: background-color 0.3s;
        }
        .delete-btn {
            background-color: #ff5252;
        }
        .delete-btn:hover {
            background-color: #ff1744;
        }
        .checkout-btn {
            background-color: #4CAF50;
        }
        .checkout-btn:hover {
            background-color: #388E3C;
        }
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 30px;
            gap: 10px;
        }
        .page-btn {
            padding: 8px 15px;
            background-color: #4285f4;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        .page-btn:hover {
            background-color: #3367d6;
        }
        .page-btn.active {
            background-color: #3367d6;
            font-weight: bold;
        }
        .page-btn.disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        @media (max-width: 768px) {
            .cart-container {
                grid-template-columns: 1fr;
            }
            .cart-item {
                height: auto;
            }
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            // 每页显示的商品数量
            const itemsPerPage = 4;
            // 当前页码
            let currentPage = 1;
            // 总商品数
            const totalItems = ${cartList.size()};
            // 总页数
            const totalPages = Math.ceil(totalItems / itemsPerPage);

            // 初始化分页
            initPagination();

            // 显示指定页的商品
            function showPage(page) {
                $('.cart-item').hide();
                $('.cart-item').slice((page-1)*itemsPerPage, page*itemsPerPage).show();
                updatePaginationButtons();
            }

            // 初始化分页按钮
            function initPagination() {
                const $pagination = $('.pagination');
                $pagination.empty();

                // 上一页按钮
                $pagination.append('<button class="page-btn prev-btn" onclick="prevPage()">上一页</button>');

                // 页码按钮
                for (let i = 1; i <= totalPages; i++) {
                    $pagination.append(`<button class="page-btn page-number" data-page="\${i}" onclick="goToPage(\${i})">\${i}</button>`);
                }

                // 下一页按钮
                $pagination.append('<button class="page-btn next-btn" onclick="nextPage()">下一页</button>');

                // 显示第一页
                showPage(1);
            }

            // 更新分页按钮状态
            function updatePaginationButtons() {
                $('.page-number').removeClass('active');
                $(`.page-number[data-page="\${currentPage}"]`).addClass('active');

                $('.prev-btn').prop('disabled', currentPage === 1);
                $('.next-btn').prop('disabled', currentPage === totalPages);

                if (currentPage === 1) {
                    $('.prev-btn').addClass('disabled');
                } else {
                    $('.prev-btn').removeClass('disabled');
                }

                if (currentPage === totalPages) {
                    $('.next-btn').addClass('disabled');
                } else {
                    $('.next-btn').removeClass('disabled');
                }
            }

            // 上一页
            window.prevPage = function() {
                if (currentPage > 1) {
                    currentPage--;
                    showPage(currentPage);
                }
            };

            // 下一页
            window.nextPage = function() {
                if (currentPage < totalPages) {
                    currentPage++;
                    showPage(currentPage);
                }
            };

            // 跳转到指定页
            window.goToPage = function(page) {
                currentPage = page;
                showPage(currentPage);
            };

            // 减号按钮点击事件
            $('.minus').click(function() {
                var $item = $(this).closest('.cart-item');
                var goodId = $item.data('goodid');

                $.ajax({
                    type: 'POST',
                    url: '/shop/cart/decreaseQuantity',
                    data: { goodId: goodId },
                    success: function(response) {
                        if (response.success) {
                            if (response.removed) {
                                $item.remove();
                                alert('商品已移除购物车');
                                location.reload();
                            } else {
                                $item.find('.count').val(response.quantity);
                                $item.find('.item-price').text('¥' + response.price);
                            }
                        } else {
                            alert('操作失败');
                        }
                    }
                });
            });

// 加号按钮点击事件
            $('.plus').click(function() {
                var $item = $(this).closest('.cart-item');
                var goodId = $item.data('goodid');

                $.ajax({
                    type: 'POST',
                    url: '/shop/cart/increaseQuantity',
                    data: { goodId: goodId },
                    success: function(response) {
                        if (response.success) {
                            $item.find('.count').val(response.quantity);
                            $item.find('.item-price').text('¥' + response.price);
                        } else {
                            alert(response.message);
                        }
                    }
                });
            });

            // 删除按钮点击事件
            $('.delete-btn').click(function () {
                var $item = $(this).closest('.cart-item');
                var goodId = $item.data('goodid');
                if (confirm('确定要删除该商品吗？')) {
                    $.ajax({
                        type: 'POST',
                        url: '/shop/cart/deleteCartItem',
                        data: { goodId: goodId },
                        success: function (response) {
                            if (response.success) {
                                $item.remove();
                                alert('商品已从购物车中删除');
                                location.reload();
                            } else {
                                alert('删除失败');
                            }
                        },
                        error: function (error) {
                            console.log('Error:', error);
                        }
                    });
                }
            });

            // 结算按钮点击事件
            // $('.checkout-btn').click(function () {
            //     var $item = $(this).closest('.cart-item');
            //     var goodId = $item.data('goodid');
            //     var cartId = $item.data('cartid');
            //     var count = parseInt($item.find('.count').val());


                <%--$.ajax({--%>
                <%--    type: 'GET',--%>
                <%--    url: '${pageContext.request.contextPath}/order/order_add',--%>
                <%--    // data: {--%>
                <%--    //     goodId: goodId,--%>
                <%--    //     cartId: cartId,--%>
                <%--    //     count: count--%>
                <%--    // },--%>
                <%--    success: function (response) {--%>
                <%--        if (response.success) {--%>
                <%--            window.location.href = '${pageContext.request.contextPath}/order/add?goodId=' + goodId +--%>
                <%--                '&cartId=' + cartId +--%>
                <%--                '&count=' + count;--%>
                <%--        } else {--%>
                <%--            alert(response.message);--%>
                <%--        }--%>
                <%--    }--%>
                <%--});--%>
            // });
            $('.checkout-btn').on('click', function () {
                var $item = $(this).closest('.cart-item');

                var goodId = $item.data('goodid');   // 来自 data-goodid="${cart.goodid}"
                var cartId = $item.data('cartid');   // 来自 data-cartid="${cart.id}"
                var count = parseInt($item.find('.count').val());

                console.log("goodId:", goodId);
                console.log("cartId:", cartId);
                console.log("count:", count);

                if (!goodId || !cartId || isNaN(count)) {
                    alert("商品信息不完整");
                    return;
                }

                window.location.href = '${pageContext.request.contextPath}/order/order_add?goodId=' + goodId +
                    '&cartId=' + cartId +
                    '&count=' + count;
            });
        });
    </script>
</head>
<body>
<h1>购物车列表</h1>
<div class="cart-wrapper">
    <div class="cart-container">
<%--        <c:forEach items="${cartList}" var="cart">--%>
<%--            <div class="cart-item" data-goodid="${cart.goodId}" data-cartid="${cart.id}">--%>
<%--                <img src="${cart.goods.image}" alt="${cart.goods.name}" class="goods-img">--%>
<%--                <div class="item-details">--%>
<%--                    <div class="item-name">${cart.goods.name}</div>--%>
<%--                    <div class="item-price">¥${cart.price}</div>--%>
<%--                    <div class="quantity-control">--%>
<%--                        <button class="minus">-</button>--%>
<%--                        <input type="text" class="count" value="${cart.count}" readonly>--%>
<%--                        <button class="plus">+</button>--%>
<%--                    </div>--%>
<%--                    <div class="action-buttons">--%>
<%--                        <button class="delete-btn">删除</button>--%>
<%--                        <button class="checkout-btn">结算</button>--%>
<%--                    </div>--%>
<%--                </div>--%>
<%--            </div>--%>
<%--        </c:forEach>--%>


    <c:forEach items="${cartList}" var="cart">
        <div class="cart-item" data-goodid="${cart.goodid}" data-cartid="${cart.id}">
<%--            <div data-cartid="${cart.id}" style="visibility: hidden;"></div>--%>
            <img src="${cart.goodimage}" alt="${cart.goodname}" class="goods-img">
            <div class="item-details">
                <div class="item-name">${cart.goodname}</div>
                <div class="item-price">¥${cart.goodprice}</div>
                <div class="quantity-control">
                    <button class="minus">-</button>
                    <input type="text" class="count" value="${cart.num}" readonly>
                    <button class="plus">+</button>
                </div>
                <div class="action-buttons">
                    <button class="delete-btn">删除</button>
                    <button class="checkout-btn">结算</button>
                </div>
            </div>
        </div>
    </c:forEach>
    </div>

    <div class="pagination"></div>
</div>
</body>
</html>